import { onUnmounted } from "vue";
import { useRoute } from "vue-router";
import { transformFlameData, flameGraphTip, genTipHtml } from "./util";
import { flamegraph } from "d3-flame-graph";
import * as d3 from "d3";
import { flameGraphData } from "@/api/exceptionDetail";
export default function useGraph({props,chartRef}) {
    // const route = useRoute();
    const getFlameGraphData = () => {
        const {
            pid: processId,
            tid: threadId,
            requestTime: timestamp,
            dstMasterip,
            server,
            srcMasterip,

        } = props.activeItem;
        console.log(props.activeItem, props.detailInfo);

        flameGraphData({
          processId,
          threadId,
          timestamp,
          masterIp: server ? dstMasterip.key : srcMasterip.key,
          // workload_name:'api-server-system'
        }).then(({data}) => {
          if (data.length) {

            const flameArray = data;
            const flameData = transformFlameData(flameArray[0]);
            console.log(flameData, 'flameData');

            generateFlameGraph(flameData);
          }
        });
    };
    // 根据数据生成火焰图
    const generateFlameGraph = (flameData) => {


        if (chartRef.value) {
            console.log(chartRef.value);

            const chart = flamegraph()
                .width(chartRef.value.clientWidth)
                .cellHeight(20)
                .transitionDuration(750)
                .transitionEase(d3.easeCubic)
                .minFrameSize(5)
                .inverted(true)
                .selfValue(false);
            const tip = flameGraphTip().html(genTipHtml);
            chart.tooltip(tip);
            d3.select("#flame-graph").datum(flameData).call(chart);
        }
    };
    // watch([props.isActive], [props.activeItem], () => {
    //     getFlameGraphData();
    // });
    onUnmounted(() => {
        d3.select("#flame-graph").selectAll("svg").remove();
    });
    return { generateFlameGraph,getFlameGraphData };
}
